import { JSONPath } from 'jsonpath-plus';
import { useState } from "react";

export const useJson = () => {

    const [jsonContent, setJsonContent] = useState('');
    const [jsonResult, setJsonResult] = useState('');
    const [jsonPath, setJsonPath] = useState('');
    const [error, setError] = useState('');

    // 格式化JSON
    const formatJson = () => {
        if (jsonContent.trim() == '') {
            return;
        }
        try {
            const parsed = JSON.parse(jsonContent);
            setJsonResult(JSON.stringify(parsed, null, 2));
            setError('');
        } catch (err) {
            setError('JSON格式错误,无法格式化');
        }
    };

    // 格式化JSON
    const zipJson = () => {
        if (jsonContent.trim() == '') {
            return;
        }
        try {
            const parsed = JSON.parse(jsonContent);
            setJsonResult(JSON.stringify(parsed));
            setError('');
        } catch (err) {
            setError('JSON格式错误,无法格式化');
        }
    };



    // 转义JSON
    const escapeJson = () => {
        if (jsonContent.trim() == '') {
            return;
        }
        try {
            // 转义双引号和反斜杠
            const escaped = jsonContent.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
            setJsonResult(escaped);
            setError('');
        } catch (err) {
            setError('转义处理失败');
        }
    };

    // 去除转义
    const unescapeJson = () => {
        if (jsonContent.trim() == '') {
            return;
        }
        try {
            // 去除转义的双引号和反斜杠
            const unescaped = jsonContent.replace(/\\\\/g, '\\').replace(/\\"/g, '"');
            setJsonResult(unescaped);
            setError('');
        } catch (err) {
            setError('去除转义失败');
        }
    };

    // 复制结果
    const copyResult = () => {
        if (jsonResult.trim() != '') {
            setJsonContent(jsonResult);
        }
    }

    // 查找JSON路径
    const findJsonPath = () => {
        if (!jsonPath.trim()) {
            return;
        }

        try {
            const parsed = JSON.parse(jsonContent);

            // 使用jsonpath-plus库查询JSON路径
            try {
                // 标准化路径，确保它是有效的JSONPath表达式
                let normalizedPath = jsonPath;

                // 如果路径不是以$开头，添加$前缀
                if (!normalizedPath.startsWith('$')) {
                    normalizedPath = '$.' + normalizedPath;
                }

                // 执行JSONPath查询
                const result = JSONPath({ path: normalizedPath, json: parsed });

                if (result.length === 0) {
                    setError(`路径 "${jsonPath}" 未找到`);
                    setJsonResult('');
                } else if (result.length === 1) {
                    // 单个结果
                    setJsonResult(typeof result[0] === 'object' ?
                        JSON.stringify(result[0], null, 2) :
                        String(result[0]));
                    setError('');
                } else {
                    // 多个结果
                    setJsonResult(JSON.stringify(result, null, 2));
                    setError('');
                }
            } catch (pathErr) {
                setError(`JSONPath表达式无效: ${pathErr instanceof Error ? pathErr.message : '未知错误'}`);
            }
        } catch (err) {
            setError('JSON格式错误或路径无效');
        }
    };

    const loadExample = () => {
        setJsonContent(`{
  "name": "张三",
  "age": 30,
  "isActive": true,
  "address": {
    "street": "北京路123号",
    "city": "上海",
    "zipcode": "200001"
  },
  "phoneNumbers": [
    {
      "type": "家庭",
      "number": "123-456-7890"
    },
    {
      "type": "工作",
      "number": "098-765-4321"
    }
  ],
  "children": null
}`);
    };

    return {
        jsonContent,
        jsonResult,
        jsonPath,
        error,
        loadExample,
        copyResult,
        setJsonContent,
        setJsonPath,
        formatJson,
        zipJson,
        escapeJson,
        unescapeJson,
        findJsonPath,
    }

}